import { observer } from "mobx-react-lite"
import { ReactNode, useMemo, useState } from "react"
import { View, TextInputProps, StyleSheet, TextInput as RNTextInput } from "react-native"
import { getColorStr, mergeStyles } from "../themes"
import { useGlobalStore } from "../mobx"
import { t } from "../utils"
import { dpw12, dpw14, dpw16, dpw24, dpw364, dpw40, dpw8 } from "../constants"

interface Props extends Omit<TextInputProps, 'style'> {
    before?: ReactNode
    after?: ReactNode
    themeStyle?: Record<string, any>
    style?: Record<string, any>
    boxStyle?: Record<string, any>
}

export const TextInput = observer((props: Props) => {
    const { before, after, style, themeStyle, placeholder,boxStyle, ...rest } = props
    const { theme, language } = useGlobalStore()
    const [isFocus, setIsFocus] = useState(false)
    
    const memoST = useMemo(() => {
        return mergeStyles({
            style: { ...styles.ipt, ...style },
            theme,
            themeStyle: { color: 'color_8', ...themeStyle }
        })
    }, [theme, style, themeStyle])

    return (
        <View style={mergeStyles({style: { ...styles.box, ...boxStyle }, theme, themeStyle: { borderBottomColor: isFocus ? 'color_1' : 'color_9' }})}>
            {before && <View style={styles.before}>{before}</View>}
            <RNTextInput
                style={memoST}
                placeholder={t(language, placeholder || '')}
                onFocus={() => {setIsFocus(true)}}
                onBlur={() => {setIsFocus(false)}}
                cursorColor={getColorStr(theme, 'color_1')}
                placeholderTextColor={getColorStr(theme, 'color_39')}
                {...rest}
            />
            {after && <View style={styles.after}>{after}</View>}
        </View>
    )
})

const styles = StyleSheet.create({
    box: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        borderBottomWidth: 1,
        borderBottomStartRadius: 2,
        marginBottom: dpw16,
        height: dpw40,
    },
    ipt: {
        height: dpw40,
        paddingVertical: dpw8,
        flex: 1,
        fontSize: dpw16,
        lineHeight: dpw24                ,
    },
    before: {
        marginRight: dpw16,
        width: dpw24,
        height: dpw24
    },
    after: {
        
    }
})